using System;
using System.Security.Cryptography;
using System.Text;

public class AES256Encode : IEncode, IDecode
{
    private string m_AESKey;
    public AES256Encode(string aesKey)
    {
        m_AESKey = aesKey;
    }
        
    
    private static byte[] AESKeys = { 0x41, 0x72, 0x65, 0x79, 0x63, 0x75, 0x4D, 0x79, 0x53, 0x6E, 0x6F, 0x76, 0x6D, 0x61, 0x3E, 0x2F };
    
    public static byte[] AESEncode(byte[] inputData, string encryptKey,Encoding encoding)
    {
        if(encryptKey.Length > 32)
            encryptKey = encryptKey.Substring(0, 32);
        
        encryptKey = encryptKey.PadRight(32, ' ');

        RijndaelManaged rijndaelProvider = new RijndaelManaged();
        rijndaelProvider.Key = encoding.GetBytes(encryptKey);
        rijndaelProvider.IV = AESKeys;
        rijndaelProvider.Mode = CipherMode.ECB;
        rijndaelProvider.Padding = PaddingMode.PKCS7;
        
        ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();

        byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);

        return encryptedData;
    }

    public static byte[] AESDecode(byte[] inputData, string decryptKey, Encoding encoding)
    {
        if(decryptKey.Length > 32)
            decryptKey = decryptKey.Substring(0, 32);
            
        decryptKey = decryptKey.PadRight(32, ' ');
        
        return AESDecode(inputData, encoding.GetBytes(decryptKey));
    }
    
    public static byte[] AESDecode(byte[] inputData, byte[] decryptKey)
    {
        try
        {     
            RijndaelManaged rijndaelProvider = new RijndaelManaged();
            rijndaelProvider.Key = decryptKey;
            rijndaelProvider.IV = AESKeys;
            rijndaelProvider.Mode = CipherMode.ECB;
            rijndaelProvider.Padding = PaddingMode.PKCS7;
            
            ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();

            byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);

            return decryptedData;
        }
        catch
        {
            return null;
        }
    }
    
    
    public byte[] Encrypt(byte[] data)
    {
        return AESEncode(data, m_AESKey,Encoding.UTF8);
    }

    public byte[] Decrypt(byte[] data)
    {
        return AESDecode(data, m_AESKey,Encoding.UTF8);
    }
}